//
//  GroupMsgDao.m
//  SportSocial
//
//  Created by yull on 15/1/22.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "GroupMsgDao.h"

@implementation GroupMsgDao

+ (instancetype)shareInstance
{
    static GroupMsgDao *groupDao = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        groupDao = [[GroupMsgDao alloc] init];
    });
    return groupDao;
}

- (void)createTable
{
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        NSArray *sqlArray = [NSArray arrayWithObjects:
                             @"CREATE TABLE IF NOT EXISTS groupMsg ("
                             "[id] integer NOT NULL PRIMARY KEY AUTOINCREMENT, "
                             "[msgNum] integer,"
                             "[sendId] integer,"
                             "[senderName] varchar,"
                             "[groupId] integer,"
                             "[content] varchar,"
                             "[decodeContent] varchar,"
                             "[createTime] integer,"
                             "[msgType] integer,"
                             "[roleType] integer,"
                             "[msgSubType] integer,"
                             "[msgLength] integer,"
                             "[isRead] integer,"
                             "[isAck] integer,"
                             "[url] varchar,"
                             "[bigImageUrl] varchar,"
                             "[localPath] varchar,"
                             "[sendStatus] integer,"
                             "[picUploadPercent] double,"
                             "[retainField] varchar,"
                             "[icon] varchar)",nil];
        [db beginTransaction];
        BOOL result = YES;
        for (NSString *sql in sqlArray) {
            result &= [db executeUpdate:sql];
        }
        if (result) {
            result &= [db commit];
        }
        
        if (!result) {
            [db rollback];
        }
    }];
}

- (BOOL)insertGroupChatMsg:(GroupChatMsg *)groupMsg
{
    __block BOOL result = YES;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"insert into groupMsg (msgNum,sendId,senderName,groupId,content,decodeContent,createTime,msgType,roleType,msgSubType,msgLength,isRead,isAck,url,bigImageUrl,localPath,sendStatus,picUploadPercent,retainField,icon) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                  [NSNumber numberWithLongLong:groupMsg.msgNum],
                  [NSNumber numberWithLongLong:groupMsg.sendId],
                  groupMsg.senderName,
                  [NSNumber numberWithLongLong:groupMsg.groupId],
                  groupMsg.content,
                  groupMsg.decodeContent,
                  [NSNumber numberWithLongLong:groupMsg.createTime],
                  [NSNumber numberWithInteger:groupMsg.msgType],
                  [NSNumber numberWithInteger:groupMsg.roleType],
                  [NSNumber numberWithInteger:groupMsg.msgSubType],
                  [NSNumber numberWithInteger:groupMsg.msgLength],
                  [NSNumber numberWithInteger:groupMsg.isRead],
                  [NSNumber numberWithInteger:groupMsg.isAck],
                  groupMsg.url,
                  groupMsg.bigImageUrl,
                  groupMsg.localPath,
                  [NSNumber numberWithInteger:groupMsg.sendStatus],
                  [NSNumber numberWithFloat:groupMsg.picUploadPercent],
                  groupMsg.retainField,
                  groupMsg.icon];
        
        if (result) {
            groupMsg.dbId = db.lastInsertRowId;
        }
    }];
    return result;
}

//更新消息发送状态
- (BOOL)updateSendStatusWithDbId:(UInt64)dbId status:(ChatMsgSendStatus)status
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update groupMsg set sendStatus=? where id=?",[NSNumber numberWithInteger:status],[NSNumber numberWithLongLong:dbId]];
    }];
    return result;
}

#pragma mark - 收到消息
- (BOOL)checkExistWithChatMsg:(GroupChatMsg *)chatMsg
{
    __block BOOL result = NO;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"select * from groupMsg where msgNum=? and roleType=?",[NSNumber numberWithLongLong:chatMsg.msgNum],
                                  [NSNumber numberWithUnsignedInteger:ChatMsgRoleTypeReceive]];
        if (resultSet.next) {
            result = YES;
            chatMsg.dbId = [resultSet longLongIntForColumn:@"id"];
        }
        [resultSet close];
    }];
    return result;
}

- (BOOL)updateChatMsg:(GroupChatMsg *)chatMsg
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update groupMsg set msgNum=?,sendId=?,senderName=?,groupId=?,content=?,decodeContent=?,createTime=?,msgType=?,roleType=?,msgSubType=?,msgLength=?,isRead=?,isAck=?,url=?,bigImageUrl=?,localPath=?,sendStatus=?,picUploadPercent=?,retainField=?,icon=? where id=?",[NSNumber numberWithLongLong:chatMsg.msgNum],
                  [NSNumber numberWithLongLong:chatMsg.sendId],
                  chatMsg.senderName,
                  [NSNumber numberWithLongLong:chatMsg.groupId],
                  chatMsg.content,
                  chatMsg.decodeContent,
                  [NSNumber numberWithLongLong:chatMsg.createTime],
                  [NSNumber numberWithInteger:chatMsg.msgType],
                  [NSNumber numberWithInteger:chatMsg.roleType],
                  [NSNumber numberWithInteger:chatMsg.msgSubType],
                  [NSNumber numberWithInteger:chatMsg.msgLength],
                  [NSNumber numberWithInteger:chatMsg.isRead],
                  [NSNumber numberWithInteger:chatMsg.isAck],
                  chatMsg.url,
                  chatMsg.bigImageUrl,
                  chatMsg.localPath,
                  [NSNumber numberWithInteger:chatMsg.sendStatus],
                  [NSNumber numberWithFloat:chatMsg.picUploadPercent],
                  chatMsg.retainField,
                  chatMsg.icon,
                  [NSNumber numberWithLongLong:chatMsg.dbId]];
    }];
    return result;
}

//更新一条接收消息
- (BOOL)addGroupMsg:(GroupChatMsg *)chatMsg
{
    BOOL exist = [self checkExistWithChatMsg:chatMsg];
    if (exist) {
        return [self updateChatMsg:chatMsg];
    }else {
        return [self insertGroupChatMsg:chatMsg];
    }
}

//接收到消息数组
- (BOOL)receiveGroupMsgArray:(NSArray *)chatMsgArray
{
    BOOL result = YES;
    
    for (GroupChatMsg *chatMsg in chatMsgArray) {
        result &= [self addGroupMsg:chatMsg];
    }
    return result;
}

//查找所有聊天
- (NSArray *)selectAllGroupMsgArrayWithGroupId:(UInt64)groupId
{
    __block NSMutableArray *msgArray = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"select * from (select * from groupMsg where groupId=? order by id desc limit(10)) order by id asc",[NSNumber numberWithLongLong:groupId]];
        while (resultSet.next) {
            [msgArray addObject:[GroupChatMsg groupMsgWithResultSet:resultSet]];
        }
        [resultSet close];
    }];
    return msgArray;
}

- (NSArray *)selectHistoryGroupMsgArrayWithGroupId:(UInt64)groupId dbId:(UInt64)dbId
{
    __block NSMutableArray *msgArray = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"select * from (select * from groupMsg where (groupId=? and id<?) order by id desc limit(10)) order by id asc",[NSNumber numberWithLongLong:groupId],[NSNumber numberWithLongLong:dbId]];
        while (resultSet.next) {
            [msgArray addObject:[GroupChatMsg groupMsgWithResultSet:resultSet]];
        }
        [resultSet close];
    }];
    return msgArray;
}

- (BOOL)updateMsgId:(UInt64)msgId preview:(NSString *)preview original:(NSString *)original
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update groupMsg set url=?,bigImageUrl=? where id=?",preview,original,[NSNumber numberWithLongLong:msgId]];
    }];
    return result;
}

- (BOOL)updateReadWithDBId:(UInt64)dbId
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update groupMsg set isRead=? where id=?",[NSNumber numberWithInteger:1],[NSNumber numberWithLongLong:dbId]];
    }];
    return result;
}

- (NSArray *)selectAllPicMsgWithGroupId:(UInt64)groupId
{
    __block NSMutableArray *array = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:@"select * from groupMsg where msgType=? and groupId=?",[NSNumber numberWithInteger:ChatMsgTypePic],[NSNumber numberWithLongLong:groupId]];
        while (result.next) {
            [array addObject:[GroupChatMsg groupMsgWithResultSet:result]];
        }
        [result close];
    }];
    return array;
}

- (BOOL)clearSendingMessageToFail
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update groupMsg set sendStatus=? where sendStatus=?",[NSNumber numberWithInteger:ChatMsgSendStatusFail],[NSNumber numberWithInteger:ChatMsgSendStatusSending]];
    }];
    return result;
}

- (BOOL)deleteAllMsgWithGroupId:(UInt64)groupId
{
    __block BOOL result = NO;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"delete from groupMsg where groupId=?",[NSNumber numberWithLongLong:groupId]];
    }];
    return result;
}
@end
